<template>
  <div class="user-management">
    <!-- 主要内容区域 -->
    <card>
      <div class="main-content">
        <!-- 左侧组织树 -->
        <div class="left-panel">
          <OrganizeTree v-model="userStore.selectedOrganizeId" @node-click="handleOrganizeClick"
            @add="handleAddOrganize" @edit="handleEditOrganize" @delete="handleDeleteOrganize" ref="organizeTreeRef" />
        </div>

        <!-- 右侧用户列表 -->
        <div class="right-panel">
          <Card>
            <template #header>
              <div class="panel-header">
                <h3>用户列表</h3>
                <div class="header-actions">
                  <el-button type="primary" @click="handleAddUser">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    新增
                  </el-button>
                  <el-button @click="handleExportUsers">
                    <el-icon>
                      <Download />
                    </el-icon>
                    导出
                  </el-button>
                  <el-button type="danger" @click="handleBatchDelete" :disabled="!userStore.hasSelectedUsers">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
              <el-input v-model="userStore.searchKeyword" placeholder="请输入姓名搜索" clearable @keyup.enter="handleSearch">
                <template #append>
                  <el-button @click="handleSearch">查询</el-button>
                </template>
              </el-input>
            </div>

            <div class="content-wrapper">
              <!-- 用户列表 -->
              <ElementTable :table-title="tableColumns" :data="userStore.userList" :showPagination="false"
                :page-config="userStore.pagination" :refresh-method="userStore.fetchUserList"
                :del-method="handleDeleteUser" :del-params="getDeleteParams" @select-change="handleSelectionChange"
                ref="tableRef">
                <!-- 部门自定义显示 -->
                <template #department="{ data }">
                  <span>{{ organizeMap.get(data.row.orgId) || `ID:${data.row.orgId}` }}</span>
                </template>

                <!-- 角色自定义显示 -->
                <template #role="{ data }">
                  <span>{{ roleMap.get(data.row.roleId) || `ID:${data.row.roleId}` }}</span>
                </template>

                <!-- 允许登录自定义显示 -->
                <template #isEnable="{ data }">
                  <span :style="{ color: data.row.isEnable ? '#67C23A' : '#F56C6C' }">
                    {{ data.row.isEnable ? '是' : '否' }}
                  </span>
                </template>
              </ElementTable>
            </div>


          </Card>
        </div>
      </div>

    </card>


    <!-- 用户编辑对话框 -->
    <UserDialog v-model:visible="userDialogVisible" :user-data="userStore.currentUser"
      :organize-id="userStore.selectedOrganizeId" :role-list="roleList"
      @success="handleUserDialogSuccess" />

    <!-- 组织编辑对话框 -->
    <OrganizeDialog v-model:visible="organizeDialogVisible" :organize-data="organizeStore.currentOrganize"
      :parent-id="userStore.selectedOrganizeId" @success="handleOrganizeDialogSuccess" />

    <!-- 重置密码对话框 -->
    <ResetPasswordDialog v-model:visible="resetPasswordDialogVisible" :user-data="userStore.currentUser"
      @success="handleResetPasswordDialogSuccess" />

    <!-- 文件上传组件 -->
    <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElButton, ElInput, ElIcon } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import OrganizeTree from '@/components/OrganizeTree.vue'
import Card from '@/components/card/index.vue'
import UserDialog from './components/UserDialog.vue'
import OrganizeDialog from './components/OrganizeDialog.vue'
import ResetPasswordDialog from './components/ResetPasswordDialog.vue'
import { useUserStore } from '@/stores/user'
import { useOrganizeStore } from '@/stores/organize'
import { error } from '@/utils/toast'
import { confirm } from '@/utils/confirm'
import { api } from '@/api'
import type { User, OrganizeTreeNode } from '@/types'
import { ExportUtil } from '@/utils/export'
// 使用stores
const userStore = useUserStore()
const organizeStore = useOrganizeStore()

// 响应式数据
const roleList = ref<any[]>([])

// 计算属性 - 创建映射关系
const roleMap = computed(() => {
  const map = new Map<number, string>()
  roleList.value.forEach(role => {
    map.set(role.roleId, role.roleName)
  })
  return map
})

const organizeMap = computed(() => {
  const map = new Map<number, string>()
  
  // 递归遍历树形结构，收集所有节点
  const collectAllNodes = (nodes: any[]) => {
    nodes.forEach(node => {
      map.set(node.id, node.name)
      if (node.children && node.children.length > 0) {
        collectAllNodes(node.children)
      }
    })
  }
  
  collectAllNodes(organizeStore.organizeTree)
  return map
})


// 对话框状态
const userDialogVisible = ref(false)
const organizeDialogVisible = ref(false)
const resetPasswordDialogVisible = ref(false)

// 组件引用
const organizeTreeRef = ref()
const tableRef = ref()
const fileInputRef = ref<HTMLInputElement>()


// 表格列配置
const tableColumns = ref<any[]>([
  {
    type: 'selection',
    width: '50',
    fn: (row: User) => row.id !== 1 // ID为1的用户不能被选中
  },
  {
    type: 'text',
    label: '姓名',
    prop: 'name',
  },

  {
    type: 'custom',
    label: '部门',
    name: 'department',
  },
  {
    type: 'custom',
    label: '角色',
    name: 'role',
  },
  {
    type: 'custom',
    label: '允许登录',
    name: 'isEnable'
  },
  {
    type: 'operate',
    label: '操作',
    width: '200',
    actions: [
      {
        name: '重置密码',
        type: 'primary',
        isLink: true,
        click: () => { } // 临时占位
      },
      {
        name: '修改',
        type: 'primary',
        isLink: true,
        click: () => { } // 临时占位
      },
      {
        name: '删除',
        type: 'danger',
        isLink: true,
        click: () => { }, // 临时占位
        showDel: (row: User) => row.id !== 1 // ID为1的用户不显示删除按钮
      }
    ]
  }
])

// 方法
// 加载角色数据
const loadRoleData = async () => {
  try {
    // 加载角色数据
    const roleResponse = await api.role.getAllRoles()
    if (roleResponse.success || roleResponse.code === 200) {
      roleList.value = roleResponse.data || []
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
  }
}

// 组织树事件处理
const handleOrganizeClick = (node: OrganizeTreeNode) => {
  userStore.setSelectedOrganizeId(node.id)
  organizeStore.setSelectedOrganize(node)
  // 加载该组织下的用户数据
  userStore.fetchUserList()
}

const handleAddOrganize = () => {
  organizeStore.setCurrentOrganize(null)
  organizeDialogVisible.value = true
}

const handleEditOrganize = (node: OrganizeTreeNode) => {
  organizeStore.setCurrentOrganize(node)
  organizeDialogVisible.value = true
}

const handleDeleteOrganize = async (node: OrganizeTreeNode) => {
  try {
    await confirm.delete(node.name, '组织')
    await organizeStore.deleteOrganize(node.id)
  } catch (err) {
    // 用户取消删除
  }
}

// 用户操作事件处理
const handleAddUser = () => {
  userStore.setCurrentUser(null)
  userDialogVisible.value = true
}

const handleEditUser = (row: User) => {
  userStore.setCurrentUser(row)
  userDialogVisible.value = true
}

// 获取删除参数
const getDeleteParams = (row: User) => {
  // 防止删除ID为1的用户（通常是管理员）
  if (row.id === 1) {
    return null // 返回null表示不允许删除
  }
  return {
    id: row.id,
    name: row.name || row.username || '用户'
  }
}

const handleDeleteUser = async (param: any) => {
  try {
    // param可能是用户ID或者用户对象
    const userId = typeof param === 'number' ? param : param.id
    await userStore.deleteUserAction(userId)
  } catch (err) {
    console.error('删除用户失败:', err)
    throw err // 重新抛出错误，让DelDialog处理
  }
}

const handleResetPassword = async (row: User) => {
  // 设置当前用户并打开重置密码弹框
  userStore.setCurrentUser(row)
  resetPasswordDialogVisible.value = true
}


// 批量操作
const handleSelectionChange = (selection: User[]) => {
  userStore.setSelectedUsers(selection)
}

const handleBatchDelete = async () => {
  if (!userStore.hasSelectedUsers) {
    error('请选择要删除的用户')
    return
  }

  // 检查是否包含ID为1的用户
  const hasAdminUser = userStore.selectedUsers.some(user => user.id === 1)
  if (hasAdminUser) {
    error('不能删除管理员用户')
    return
  }

  try {
    await confirm.batch('删除', userStore.selectedUsers.length, '用户')
    await userStore.batchDeleteUsersAction(userStore.selectedUserIds)
  } catch (err) {
    if (err !== 'cancel') {
      error('批量删除失败')
    }
  }
}

// 导入导出
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  try {
    await confirm.confirm('确定要导入用户数据吗？', '导入用户')
    await userStore.importUsersAction(file)
  } catch (err) {
    if (err !== 'cancel') {
      error('导入失败')
    }
  } finally {
    target.value = ''
  }
}

const handleExportUsers = async () => {
  try {
    const response = await userStore.exportUsersAction()
    ExportUtil.handleApiResponse(response, {
      filename: ExportUtil.generateFilename('用户数据'),
      fileType: 'csv'
    })
  } catch (err) {
    error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  userStore.searchUsers(userStore.searchKeyword)
}

// 对话框成功回调
const handleUserDialogSuccess = () => {
  userDialogVisible.value = false
}

const handleOrganizeDialogSuccess = () => {
  organizeDialogVisible.value = false
}

const handleResetPasswordDialogSuccess = () => {
  resetPasswordDialogVisible.value = false
}

// 组件挂载
onMounted(async () => {
  // 更新表格列配置中的事件处理函数
  if (tableColumns.value[5]?.actions) {
    tableColumns.value[5].actions[0].click = (row: User, _column: any) => handleResetPassword(row)
    tableColumns.value[5].actions[1].click = (row: User, _column: any) => handleEditUser(row)
    // 删除操作通过del-method属性处理，不需要在这里设置
  }

  // 加载角色数据
  loadRoleData()

  // 初始化组织树数据
  await organizeStore.fetchOrganizeTree()

  // 如果组织树加载完成且有数据，自动选择第一个组织
  if (organizeStore.organizeTree && organizeStore.organizeTree.length > 0) {
    const firstOrganize = organizeStore.organizeTree[0]
    userStore.setSelectedOrganizeId(firstOrganize.id)
    organizeStore.setSelectedOrganize(firstOrganize)
    // 加载该组织下的用户数据
    await userStore.fetchUserList()
  }
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.top-banner {
  padding: 8px 16px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 16px;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  overflow: hidden;
}

.left-panel {
  width: 300px;
  flex-shrink: 0;
}

.right-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.search-area {
  margin-bottom: 16px;

  .el-input {
    width: 300px;
  }
}

.content-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}
</style>